package org.example.user.flight;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class searchBlock extends JFrame {
    private JTextField departureField, arrivalField;
    private JButton addButton;
    public static int airwayId;

    public searchBlock() {
        setTitle("管理端航班查询的输入页面");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(9, 2));

        JLabel departureLabel = new JLabel("起点");
        departureField = new JTextField();

        JLabel arrivalLabel = new JLabel("终点");
        arrivalField = new JTextField();

        addButton = new JButton("搜索");

        // 添加组件到窗口00
        add(departureLabel);
        add(departureField);

        add(arrivalLabel);
        add(arrivalField);

        add(new JLabel()); // 占位
        add(addButton);

        // 添加添加按钮的点击事件监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addUserInfoToDatabase();
                SwingUtilities.invokeLater(() -> {
                    searchFlightView searchFlightForm = new searchFlightView();
                    searchFlightForm.setSize(400, 300);
                    searchFlightForm.setVisible(true);
                });
            }
        });
    }

    private void addUserInfoToDatabase() {
        String departure2 = departureField.getText();
        String arrival2 = arrivalField.getText();

        try {
            // 连接数据库
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/airlines", "root", "123456");
            Statement statement=conn.createStatement();

            // 创建插入语句
            String Query = "SELECT airway_id FROM air_airway WHERE departure = '" + departure2 + "' AND arrival = '" + arrival2 + "'";
            ResultSet resultSet=statement.executeQuery(Query);
            // 执行插入操作
            while (resultSet.next()) {
                airwayId= resultSet.getInt("airway_id");
            }
            // 关闭连接和语句
            statement.close();
            conn.close();

            // 清空输入框
            clearFields();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void clearFields() {

    }

//    public static void main(String[] args) {
//        SwingUtilities.invokeLater(() -> {
//            searchBlock addFlightForm = new searchBlock();
//            addFlightForm.setSize(400, 300);
//            addFlightForm.setVisible(true);
//        });
//    }
}